import axios from 'axios'
import { VueAxios } from './axios'
import { useUserStore } from '@/store';
import { message } from 'ant-design-vue';




export const ResponseErrorStatus = new Map([
  [401, '身份验证过期，即将返回登录页重新登录！'],
  [500, '服务器错误']
]);


// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_SERVER_URL,
  timeout: 10000 // 请求超时时间
})

// request interceptor
service.interceptors.request.use(config => {
  const userStore = useUserStore();

  const authToken = userStore.getToken
  if (authToken) {
    config.headers['X-Auth-Token'] = `authToken`
  }
  return config
}, error => Promise.reject(error));

// response interceptor
service.interceptors.response.use(response => {
  return response.data
}, error => {
  const { response } = error
  const data = typeof response.data === 'string' ? JSON.parse(response.data) : response.data
  if (response.status !== 200) {
    !response.config?.noMsg && message.error(data.message || ResponseErrorStatus.get(response.status) || '请求出错，请稍后重试');
  }
  return Promise.reject(error)
})

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service)
  }
}



export {
  installer as VueAxios,
  service as axios
}


